<template>
  <div class="myupload" v-loading="loading">
    <el-card shadow="always" class="mb20">
      <el-row justify="space-around">
        <template v-if="data.cover">
          <img :src="data.cover" class="albuncover" style="object-fit: contain; max-width: 150px; max-height: 150px; width: auto; height: auto;" />
        </template>
        <template v-else>
          <div class="albuncover no-photo" style="width: 150px; height: 150px; display: flex; align-items: center; justify-content: center; background-color: #f5f7fa; border: 1px dashed #d9d9d9; border-radius: 4px;">暂无封面</div>
        </template>
        <div :style="{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }">
          <h1>{{ `相册名称${data.name} ————— 相片数量${data.total}张` }}</h1>
          <h3>{{ data.description }}</h3>
        </div>
        <div style="width: 350px; display: flex; align-items: center; gap: 10px;">
<!--          {{ checkids }}-->
<!--          <el-button type="primary" @click="moreMove">移动</el-button>-->
<!--          <el-select v-model="movetoalbum" placeholder="选择相册" size="large" style="width: 200px">-->
<!--            <el-option v-for="item in moveTo" :key="item.value" :label="item.label" :value="item.value" />-->
<!--          </el-select>-->
          <el-button  size="small" v-if="!Boolean(route.query.id === 0)" type="danger" @click="moreDel">删除</el-button>
          <el-popconfirm @confirm="moreDel" v-else title="默认相册删除将永远删除">
            <template #reference>
              <el-button>Delete</el-button>
            </template>
          </el-popconfirm>
          <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
        </div>
      </el-row>
    </el-card>
    <n-upload
      :disabled="disabledmy"
      :custom-request="handlereq"
      accept="image/*"
      :default-file-list="fileList"
      list-type="image-card"
      @change="handleUploadChange"
      @remove="handleRemove"
      ref="myupload"
      multiple
      :keep-file-after-finsh="true"
      :file-list-style="{ width: '100%', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', justifyContent: 'center' }"
    >
      点击上传
    </n-upload>
    <n-modal v-model:show="showModal" preset="card" style="width: 600px" title="一张很酷的图片">
      <img :src="previewImageUrl" style="width: 100%" />
    </n-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { NUpload, NModal } from "naive-ui";
import qiniuAPI from "/@/api/qiniu";
import Cookies from "js-cookie";
import * as qiniu from "qiniu-js";
import albumapi from "/@/api/managealbum";
import { useRoute } from "vue-router";
import { delPhotos, movePhotos } from "/@/views/album/album";

const route = useRoute();
const showModal = ref(false);
const previewImageUrl = ref("");
const myupload = ref(null);
const fileList = ref([]);
const loading = ref(true);
const data = reactive({
  cover: "",
  name: "",
  total: route.query.total,
  description: ""
});
const morecheck = ref(false);
const checkLinks = ref([]);
const disabledmy = ref(false);
const moveTo = ref([]);
const movetoalbum = ref(null);
const checkids = computed(() =>
  fileList.value
    .map((f) => {
      if (checkLinks.value.includes(f.url)) return f.id;
    })
    .filter((i) => i)
);
const selectAll = ref(false);
const handleUploadChange = (data) => {
  // 为新上传的照片添加复选框
  setTimeout(() => {
    const nodelist = myupload.value.$el.children[1].querySelectorAll(".n-upload-file");
    const lastNode = nodelist[nodelist.length - 1];
    if (lastNode) {
      let link = lastNode.querySelector("img").src;
      let oDiv = document.createElement("input");
      oDiv.classList = "checkimg";
      oDiv.type = "checkbox";
      oDiv.dataset.link = link;
      oDiv.addEventListener("click", (e) => {
        const flag = e.target.checked;
        const link = e.target.dataset.link;
        if (flag) {
          checkLinks.value.push(link);
        } else {
          checkLinks.value = checkLinks.value.filter((item) => item !== link);
        }
        // 更新全选状态
        updateSelectAllState();
      });
      lastNode.appendChild(oDiv);
    }
  }, 0);
};
const handleRemove = ({ file }) => {
  console.log(file);
  albumapi
    .delPhotos(
      [file.id]
    )
    .then((result) => {
      console.log(result);
    });
};
const handleSelectAll = () => {
  const nodelist = myupload.value.$el.children[1].querySelectorAll(".n-upload-file");
  const nodeArrry = Array.from(nodelist);

  // 清空之前的选中状态
  checkLinks.value = [];

  // 为每个图片添加或更新复选框
  for (let item of nodeArrry) {
    let link = item.querySelector("img").src;
    let existingCheckbox = item.querySelector(".checkimg");

    if (!existingCheckbox) {
      let oDiv = document.createElement("input");
      oDiv.classList = "checkimg";
      oDiv.type = "checkbox";
      oDiv.dataset.link = link;
      oDiv.addEventListener("click", (e) => {
        const flag = e.target.checked;
        const link = e.target.dataset.link;
        if (flag) {
          checkLinks.value.push(link);
        } else {
          checkLinks.value = checkLinks.value.filter((item) => item !== link);
        }
        // 更新全选状态
        updateSelectAllState();
      });
      item.appendChild(oDiv);
    }

    // 根据selectAll状态设置复选框
    const checkbox = item.querySelector(".checkimg");
    if (checkbox) {
      checkbox.checked = selectAll.value;
      if (selectAll.value) {
        checkLinks.value.push(link);
      }
    }
  }

  disabledmy.value = selectAll.value;

  // 显示选中数量提示
  if (selectAll.value) {
    ElMessage({
      message: `已全选 ${checkLinks.value.length} 张照片`,
      type: "success"
    });
  } else {
    ElMessage({
      message: "已取消全选",
      type: "info"
    });
  }
};

// 更新全选状态
const updateSelectAllState = () => {
  const nodelist = myupload.value.$el.children[1].querySelectorAll(".n-upload-file");
  const nodeArrry = Array.from(nodelist);
  const allChecked = nodeArrry.every(item => {
    const checkbox = item.querySelector(".checkimg");
    return checkbox && checkbox.checked;
  });
  selectAll.value = allChecked;

  // 显示当前选中数量
  const selectedCount = checkLinks.value.length;
  if (selectedCount > 0) {
    ElMessage({
      message: `已选中 ${selectedCount} 张照片`,
      type: "info",
      duration: 1000
    });
  }
};

// 初始化时添加复选框
const initCheckboxes = () => {
  setTimeout(() => {
    const nodelist = myupload.value.$el.children[1].querySelectorAll(".n-upload-file");
    const nodeArrry = Array.from(nodelist);
    for (let item of nodeArrry) {
      let link = item.querySelector("img").src;
      let oDiv = document.createElement("input");
      oDiv.classList = "checkimg";
      oDiv.type = "checkbox";
      oDiv.dataset.link = link;
      oDiv.addEventListener("click", (e) => {
        const flag = e.target.checked;
        const link = e.target.dataset.link;
        if (flag) {
          checkLinks.value.push(link);
        } else {
          checkLinks.value = checkLinks.value.filter((item) => item !== link);
        }
        // 更新全选状态
        updateSelectAllState();
      });
      item.appendChild(oDiv);
    }
  }, 0);
};

const moreDel = () => {
  console.log(checkids.value);
  if (!checkids.value.toString()) {
    ElMessage({
      message: "请选择照片",
      type: "warning"
    });
    return;
  }
  delPhotos(checkids.value)
    .then((result) => {
      // const files = fileList.value.filter((item) => !checkids.value.includes(item.id));
      const files = fileList.value;
      checkids.value.forEach((item) => {
        let delindex;
        for (let index = 0; index < files.length; index++) {
          const element = files[index];
          if (element.id == item) {
            delindex = index;
            break;
          }
        }
        fileList.value.splice(delindex, 1);
      });
      checkLinks.value = [];
      initData()
    });
};
/*const moreMove = () => {
  if (!movetoalbum.value) {
    ElMessage({
      message: "请选择目标相册",
      type: "warning"
    });
    return;
  }
  if (checkids.value.length === 0) {
    ElMessage({
      message: "请选择照片",
      type: "warning"
    });
    return;
  }
  movePhotos({
    ids: checkids.value,
    albumId: movetoalbum.value
  })
    .then((res) => {
      const files = fileList.value;
      checkids.value.forEach((item) => {
        let delindex;
        for (let index = 0; index < files.length; index++) {
          const element = files[index];
          if (element.id == item) {
            delindex = index;
            break;
          }
        }
        fileList.value.splice(delindex, 1);
      });
      checkLinks.value = [];
    });
  movetoalbum.value = null;
};*/

const initData = () => {
  albumapi.getPhotosByAlbumId(route.query.id).then((res) => {
    moveTo.value = res.albums;
    data.cover = res.photos[0] ? res.photos[0].link : null;
    data.name = res.albumInfo.name;
    data.description = res.albumInfo.description;
    let filedefault = res.photos.map((item) => {
      return {
        id: item.id,
        name: item.name,
        status: "finished",
        url: item.link
      };
    });
    for (let item of filedefault) {
      fileList.value.push(item);
    }
    loading.value = false;

    // 初始化时添加复选框
    initCheckboxes();
  });
};
initData();
const handlereq = ({ file, onProgress, onFinish, onError }) => {
  qiniuAPI
    .getToken()
    .then((res) => {
      const token = res;
      console.log(token);
      let type = "";
      if (file.name) {
        const num = file.name.split(".");
        type = num[num.length - 1];
      } else {
        type = file.type.split("/")[1];
      }
      const key = "test/" + Cookies.get("yourStuNum") + Date.now() + "." + type;
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      };
      const putExtra = {
        fname: file.name,
        params: {},
        mimeType: ["image/png", "image/jpeg", "image/gif"]
      };
      if (file.raw) {
        file = file.raw;
      }
      const observable = qiniu.upload(file.file, key, token, putExtra, config);
      const observer = {
        next(res) {
          onProgress({ percent: Math.ceil(res.total.percent) });
        },
        error(err) {
          onError();
        },
        complete(res) {
          onFinish();
          const myfile = file;
          albumapi
            .uploadPhotos({
              albumId: route.query.id,
              link: "http://img.pzhuweb.cn/" + res.key,
              name: file.name
            })
            .then((res) => {
              const file = fileList.value.find((item) => item.id === myfile.id);
              file.url = res.data.link;
              file.id = res.data.id;

              // 为新上传的照片添加复选框
              setTimeout(() => {
                const nodelist = myupload.value.$el.children[1].querySelectorAll(".n-upload-file");
                const lastNode = nodelist[nodelist.length - 1];
                if (lastNode) {
                  let link = lastNode.querySelector("img").src;
                  let oDiv = document.createElement("input");
                  oDiv.classList = "checkimg";
                  oDiv.type = "checkbox";
                  oDiv.dataset.link = link;
                  oDiv.addEventListener("click", (e) => {
                    const flag = e.target.checked;
                    const link = e.target.dataset.link;
                    if (flag) {
                      checkLinks.value.push(link);
                    } else {
                      checkLinks.value = checkLinks.value.filter((item) => item !== link);
                    }
                  });
                  lastNode.appendChild(oDiv);
                }
              }, 0);
            });
        }
      };
      const subscription = observable.subscribe(observer);
    })
    .catch((err) => {
      onError();
    });
};
</script>
<style scoped lang="less">
.myupload {
  width: 100%;

  .albuncover {
    height: 100px;
    width: 100px;
    transition: all ease 0.3s;

    &:hover {
      box-shadow: 0 2px 12px var(--next-color-dark-hover);
      cursor: pointer;
      transform: scale(1.1);
    }
  }

  .no-photo {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
    font-size: 14px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
  }
}

:deep(.n-upload-file) {
  width: 180px !important;
  height: 200px !important;
  position: relative;
  margin: 8px !important;
  display: inline-block !important;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

:deep(.n-upload-trigger) {
  width: 180px !important;
  height: 200px !important;
  display: inline-block !important;
}

:deep(.n-upload-file-list) {
  display: flex !important;
  flex-wrap: wrap !important;
  gap: 10px !important;
  justify-content: flex-start !important;
}

:deep(.n-upload-file-list .n-upload-file:hover) {
  background-color: transparent !important;
}

:deep(.n-upload-file-list .n-upload-file.n-upload-file--image-card-type::before) {
  position: relative;
}

:deep(.checkimg) {
  position: absolute !important;
  top: 10px;
  right: 10px;
  width: 20px;
  height: 20px;
  z-index: 2;
  cursor: pointer;
  appearance: none;
  background-color: rgba(255, 255, 255, 0.8);
  border: 2px solid #409EFF;
  border-radius: 4px;
  transition: all 0.3s ease;

  &:checked {
    background-color: #409EFF;
    border-color: #409EFF;
    position: relative;

    &::after {
      content: '✓';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: white;
      font-size: 14px;
    }
  }

  &:hover {
    border-color: #66b1ff;
  }
}
</style>
